package com.example.blueconn.fragment.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.example.blueconn.data.DeviceItemData;
import com.example.blueconn.data.ItemData;

import java.util.List;

public class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.DeviceViewHolder> {

    private List<DeviceItemData> itemDataList;
    private int resId;
    private DataBindDelegate<ItemData> bindDelegate;

    public DeviceAdapter(@LayoutRes int resId, DataBindDelegate<ItemData> delegate, List<DeviceItemData> data) {
        this.resId = resId;
        this.bindDelegate = delegate;
        this.itemDataList = data;
    }

    @NonNull
    @Override
    public DeviceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//        View view = LayoutInflater.from(parent.getContext())
//                .inflate(R.layout.device_item_data_show, parent, false);
        ViewDataBinding dataBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
                resId, parent, false);
        return new DeviceViewHolder(dataBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull DeviceViewHolder holder, int position) {
        bindDelegate.onBind(holder.getDataBiding(), itemDataList.get(position), position);
    }

    @Override
    public int getItemCount() {
        return itemDataList == null ? 0 : itemDataList.size();
    }

    public void setDataSource(List<DeviceItemData> list) {
        if (list != null) {
            itemDataList.clear();
            itemDataList.addAll(list);
            this.notifyDataSetChanged();
        }
    }

    public void reBuildLayout(int resId) {
        this.resId = resId;
        for (int i = 0; i < itemDataList.size(); i++) {
            notifyItemChanged(i);
        }
    }

    public class DeviceViewHolder extends RecyclerView.ViewHolder {

        private ViewDataBinding dataBinding;

        public DeviceViewHolder(@NonNull ViewDataBinding dataBinding) {
            super(dataBinding.getRoot());
            this.dataBinding = dataBinding;
        }

        public ViewDataBinding getDataBiding() {
            return dataBinding;
        }
    }
}
